package user

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserDataLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetUserDataLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetUserDataLogic {
	return &GetUserDataLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetUserDataLogic) GetUserData(req *types.GetUserDataReq) (resp *types.GetUserDataResp, err error) {
	userDataResp, err := l.svcCtx.UserRpc.GetUserData(l.ctx, &syspb.GetUserDataReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var (
		user           = new(types.SysUser)
		checkedRoleIds = make([]int64, 0)
		checkedPostIds = make([]int64, 0)
	)

	if userDataResp.GetUser() != nil {
		_ = copier.Copy(user, userDataResp.GetUser())
	}
	if len(userDataResp.GetRoleIds()) != 0 {
		checkedRoleIds = userDataResp.GetRoleIds()
	}
	if len(userDataResp.GetPostIds()) != 0 {
		checkedPostIds = userDataResp.GetPostIds()
	}

	return &types.GetUserDataResp{
		User:           user,
		CheckedRoleIds: checkedRoleIds,
		CheckedPostIds: checkedPostIds,
	}, nil
}
